// This file is part of gimcopy.
// 
// gimcopy is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
// 
// gimcopy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License along with gimcopy. If not, see <https://www.gnu.org/licenses/>. 

#include <gtk/gtk.h>
#include <gio/gunixinputstream.h>
#include <gio/gunixoutputstream.h>
void get(GtkClipboard *clipboard, GtkSelectionData *sel, guint info, gpointer data){
  GdkPixbuf *pix = (GdkPixbuf*)data;
  gtk_selection_data_set_pixbuf(sel, pix);
}

void clear(GtkClipboard *clipboard, gpointer data){
  GdkPixbuf *pix = (GdkPixbuf*)data;
  g_object_unref(pix);
  gtk_main_quit();
}
enum opmode { COPY, PASTE };
int main(int argc, char **argv){
  gtk_init(&argc, &argv);
  int mode = COPY;
  for (int i = 1; i < argc; i ++){
    if (!strcmp(argv[i], "-p")){
      mode = PASTE;
    }
  }
  GtkClipboard *clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
  GError *err = NULL;
  if (mode == COPY){
    GInputStream *gis = g_unix_input_stream_new(fileno(stdin), TRUE);
    GdkPixbuf *pix = gdk_pixbuf_new_from_stream(gis, NULL, &err);
    if (!G_IS_OBJECT(pix)) return 1;
    GtkTargetList *list = gtk_target_list_new(NULL, 0);
    gtk_target_list_add_image_targets(list, 0, TRUE);
    int n_targets;
    GtkTargetEntry *table = gtk_target_table_new_from_list(list, &n_targets);
    gtk_clipboard_set_with_owner(clipboard, table, n_targets, get, clear, G_OBJECT(pix));
  
    gtk_target_table_free(table, n_targets);
    gtk_target_list_unref(list);

    gtk_main();
  } else if (mode == PASTE){
    GOutputStream *gos = g_unix_output_stream_new(fileno(stdout), TRUE);
    GdkPixbuf *pix = gtk_clipboard_wait_for_image(clipboard);
    if (!G_IS_OBJECT(pix)) return 1;
    gdk_pixbuf_save_to_stream(pix, gos, "png", NULL, &err, NULL);
  }
}
